package com.fishingwithme.android.ui.screens.my

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.AuditCircle
import com.fishingwithme.android.data.model.CandidateUser
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.AddCircleAuditViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddCircleAuditScreen(
    onDismiss: () -> Unit,
    viewModel: AddCircleAuditViewModel = hiltViewModel()
) {
    val userSearchResults by viewModel.userSearchResults.collectAsState()
    val isUserSearching by viewModel.isUserSearching.collectAsState()
    
    val circleSearchResults by viewModel.circleSearchResults.collectAsState()
    val isCircleSearching by viewModel.isCircleSearching.collectAsState()
    
    val isSubmitting by viewModel.isSubmitting.collectAsState()
    val submitResult by viewModel.submitResult.collectAsState()
    
    var selectedUser by remember { mutableStateOf<CandidateUser?>(null) }
    var selectedCircle by remember { mutableStateOf<AuditCircle?>(null) }
    
    var userSearchQuery by remember { mutableStateOf(selectedUser?.nickname ?: "") }
    var circleSearchQuery by remember { mutableStateOf(selectedCircle?.title ?: "") }
    
    LaunchedEffect(submitResult) {
        if (submitResult is AddCircleAuditViewModel.SubmitResult.Success) {
            // Dismiss after successful submission
            onDismiss()
        }
    }
    
    // Auto search when queries change
    LaunchedEffect(userSearchQuery) {
        if (userSearchQuery.isNotEmpty()) {
            viewModel.searchUsers(userSearchQuery)
        } else {
            // Clear results when query is empty
        }
    }
    
    LaunchedEffect(circleSearchQuery) {
        if (circleSearchQuery.isNotEmpty()) {
            viewModel.searchCircles(circleSearchQuery)
        } else {
            // Clear results when query is empty
        }
    }
    
    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = SheetState(skipPartiallyExpanded = true),
        shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // Title
            Text(
                text = stringResource(R.string.add_circle_audit),
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                textAlign = TextAlign.Center
            )
            
            // User search section
            Text(
                text = stringResource(R.string.search_user),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            OutlinedTextField(
                value = userSearchQuery,
                onValueChange = { userSearchQuery = it },
                label = { Text(stringResource(R.string.enter_nickname)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 8.dp),
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.Search,
                        contentDescription = null
                    )
                },
                trailingIcon = {
                    if (userSearchQuery.isNotEmpty()) {
                        IconButton(onClick = { 
                            userSearchQuery = ""
                            selectedUser = null
                        }) {
                            Icon(
                                imageVector = Icons.Default.Clear,
                                contentDescription = stringResource(R.string.clear)
                            )
                        }
                    }
                }
            )
            
            if (isUserSearching) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(100.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else if (userSearchResults.isNotEmpty()) {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(max = 150.dp)
                        .padding(bottom = 16.dp)
                ) {
                    items(userSearchResults) { user ->
                        UserItem(
                            user = user,
                            isSelected = selectedUser?.userId == user.userId,
                            onClick = { 
                                selectedUser = user
                                userSearchQuery = user.nickname // Fill the field with selected nickname
                            }
                        )
                    }
                }
            } else if (userSearchQuery.isNotEmpty()) {
                Text(
                    text = stringResource(R.string.no_users_found),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                        .height(50.dp),
                    textAlign = TextAlign.Center
                )
            }
            
            // Circle search section
            Text(
                text = stringResource(R.string.search_circle),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            OutlinedTextField(
                value = circleSearchQuery,
                onValueChange = { circleSearchQuery = it },
                label = { Text(stringResource(R.string.enter_circle_title)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 8.dp),
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.Search,
                        contentDescription = null
                    )
                },
                trailingIcon = {
                    if (circleSearchQuery.isNotEmpty()) {
                        IconButton(onClick = { 
                            circleSearchQuery = ""
                            selectedCircle = null
                        }) {
                            Icon(
                                imageVector = Icons.Default.Clear,
                                contentDescription = stringResource(R.string.clear)
                            )
                        }
                    }
                }
            )
            
            if (isCircleSearching) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(100.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else if (circleSearchResults.isNotEmpty()) {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(max = 150.dp)
                        .padding(bottom = 16.dp)
                ) {
                    items(circleSearchResults) { circle ->
                        CircleItem(
                            circle = circle,
                            isSelected = selectedCircle?.id == circle.id,
                            onClick = { 
                                selectedCircle = circle
                                circleSearchQuery = circle.title // Fill the field with selected title
                            }
                        )
                    }
                }
            } else if (circleSearchQuery.isNotEmpty()) {
                Text(
                    text = stringResource(R.string.no_circles_found),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                        .height(50.dp),
                    textAlign = TextAlign.Center
                )
            }
            
            // Selected items summary
            if (selectedUser != null || selectedCircle != null) {
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Column(modifier = Modifier.padding(16.dp)) {
                        if (selectedUser != null) {
                            Text(
                                text = stringResource(R.string.selected_user),
                                style = MaterialTheme.typography.titleSmall,
                                fontWeight = FontWeight.Bold
                            )
                            Text(
                                text = "${selectedUser!!.nickname} (${selectedUser!!.userId})",
                                style = MaterialTheme.typography.bodyMedium,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                        
                        if (selectedCircle != null) {
                            Text(
                                text = stringResource(R.string.selected_circle),
                                style = MaterialTheme.typography.titleSmall,
                                fontWeight = FontWeight.Bold,
                                modifier = Modifier.padding(top = 8.dp)
                            )
                            Text(
                                text = "${selectedCircle!!.title} (${selectedCircle!!.id}) - ${selectedCircle!!.city}",
                                style = MaterialTheme.typography.bodyMedium,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                    }
                }
            }
            
            // Submit and Cancel buttons
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 8.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                OutlinedButton(
                    onClick = onDismiss,
                    enabled = !isSubmitting,
                    modifier = Modifier.weight(1f)
                ) {
                    Text(stringResource(R.string.cancel))
                }
                
                Spacer(modifier = Modifier.width(16.dp))
                
                Button(
                    onClick = {
                        selectedUser?.let { user ->
                            selectedCircle?.let { circle ->
                                viewModel.submitAudit(
                                    nickname = user.nickname,
                                    userId = user.userId,
                                    circleName = circle.title,
                                    circleId = circle.id
                                )
                            }
                        }
                    },
                    enabled = selectedUser != null && selectedCircle != null && !isSubmitting,
                    modifier = Modifier.weight(1f)
                ) {
                    if (isSubmitting) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(16.dp),
                            strokeWidth = 2.dp
                        )
                    } else {
                        Text(stringResource(R.string.submit))
                    }
                }
            }
            
            // Show submission result
            submitResult?.let { result ->
                when (result) {
                    is AddCircleAuditViewModel.SubmitResult.Success -> {
                        Text(
                            text = result.message,
                            color = MaterialTheme.colorScheme.primary,
                            style = MaterialTheme.typography.bodyMedium,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 16.dp),
                            textAlign = TextAlign.Center
                        )
                    }
                    is AddCircleAuditViewModel.SubmitResult.Error -> {
                        Text(
                            text = result.message,
                            color = MaterialTheme.colorScheme.error,
                            style = MaterialTheme.typography.bodyMedium,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 16.dp),
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }
            
            // Add some bottom padding to ensure buttons are visible
            Spacer(modifier = Modifier.height(16.dp))
        }
    }
}

@Composable
private fun UserItem(
    user: CandidateUser,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    ListItem(
        headlineContent = { Text(user.nickname) },
        supportingContent = { Text(user.userId) },
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .then(
                if (isSelected) {
                    Modifier.background(MaterialTheme.colorScheme.primaryContainer)
                } else {
                    Modifier
                }
            )
            .padding(horizontal = 8.dp, vertical = 4.dp)
    )
}

@Composable
private fun CircleItem(
    circle: AuditCircle,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    ListItem(
        headlineContent = { Text(circle.title) },
        supportingContent = { 
            Text("${circle.id} - ${circle.city}")
        },
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .then(
                if (isSelected) {
                    Modifier.background(MaterialTheme.colorScheme.primaryContainer)
                } else {
                    Modifier
                }
            )
            .padding(horizontal = 8.dp, vertical = 4.dp)
    )
}